package login;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2022-10-18
 * Time: 15:09
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        //读取请求中的参数，判定当前用户的身份信息是否正确
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if(username==null||password==null||username.equals("")||password.equals("")) {
            resp.getWriter().write("用户名或者密码不完整，登录失败");
            return;
        }
        //验证用户名密码是否正确
        //一般来说用户名密码是否存在于数据中的
        if(!username.equals("卢世杰")||!password.equals("123")) {
            //登录失败
            resp.getWriter().write("用户名密码错误，登录失败");
            return;
        }
        //登录成功
        //就需要创建一个会话（session)，把用户信息，填写到session中
        HttpSession session = req.getSession(true);
        session.setAttribute("username","卢世杰");
        //第二个参数是Object类型，虽然写的是0，但是要自动装箱成Integer，所以取得时候也是取出Integer
        Integer visitCount=(Integer) session.getAttribute("visitCount");
        if(visitCount==null) {
            session.setAttribute("visitCount",0);
        }
        //让页面跳转到登录页面，这里的重定向跳转，是Get请求
        resp.sendRedirect("index");
    }
}
